<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/4
 * Time: 9:58
 */

namespace app\api\controller;


use app\api\model\special\SpecialColumn;
use app\api\model\special\UserSubscribeSpecial;
use app\api\model\user\Users;
use app\common\controller\Base;
use app\common\model\ApiResponse;
use app\common\model\app\Banner;
use app\common\model\Tag;
use app\common\model\teacher\Teacher;
use app\common\model\teacher\TeacherEssay;
use app\common\model\teacher\TeacherEssayCatalog;
use app\common\model\teacher\TeacherSpeaking;
use app\common\model\Topic;
use app\common\model\UserCreditRecord;
use app\common\utils\DateTimeUtil;
use think\Db;
use think\db\Query;
use think\Request;
use think\Validate;


class Teachers extends Base
{
    private static function getPage($form) {

        $page = intval($form['page'] ?? 1);
        if ($page <= 0) $page = 1;

        $rows = intval($form['rows'] ?? self::LIMIT_DEFAULT);
        return [
            'limit' => $rows,
            'offset' => intval(($page - 1) * $rows),
        ];
    }


    /**
     * 随机获取几个老师
     *
     * @return ApiResponse
     */
    public function rand() {
        $form = $this->getAndCheckForm([
            ['limit', 'integer',],
        ]);
        return ApiResponse::success(Teacher::rand(intval($form['limit'] ?? 3)));
    }

    /**
     * 获取推荐老师
     *
     * @return ApiResponse
     */
    public function recommend() {
        $form = $this->getAndCheckForm([
            ['num', 'integer',],
        ]);
        $list = Teacher::recommended($form['num']??3);
        return ApiResponse::success($list);
    }

    /**
     * 老师列表
     * 可以分页
     * @return ApiResponse
     */
    public function list() {

        $uid = checkUserToken();

        $form = $this->getAndCheckForm([
            ['page', '^\\d+$', ],
            ['rows', '^\\d+$', ],
        ]);

        $params = self::pageFormat($form);
        $list = Teacher::apiList($params['limit'], $params['offset'], $uid);

        foreach ($list as & $item) {
            $tags = Tag::getByTeacher($item['id']);
            $item['tags'] = array_column($tags,'title');
        }

        if ($this->isPC()) {
            return ApiResponse::success($list, Teacher::apiTotal(), $params['limit']);
        } else {
            return ApiResponse::success($list);
        }
    }

    /**
     * 获取老师详情接口
     *
     * @return ApiResponse
     */
    public function detail() {

        $form = $this->getAndCheckForm([
            ['teacher_id', 'require|^\\d+$', '老师id不能为空|参数类型不正确'],
        ]);

        $teacher_id = intval($form['teacher_id']);
        $uid = checkUserToken();

        $teacher = Teacher::detail($teacher_id, $uid);

        // 老师文章总数统计
        $articleCount = Db::table('teacher_essay')->where('teacher_id', $form['teacher_id'])->where('hide', 'false')->count();
        $teacher['article_total'] = $articleCount;

        if ($teacher && $this->isPC()) {
            $teacher['latest_topic'] = Topic::getLatest($teacher['id']);
        }
        return ApiResponse::success($teacher);
    }

    /**
     * 资讯分类
     * @return ApiResponse
     */
    public function essay_catalogs() {
        return ApiResponse::success(TeacherEssayCatalog::apiList());
    }

    /**
     * 大咖观点策略、资讯
     *
     * @return ApiResponse
     */
    public function essay() {

        $uid = checkUserToken();

        $form = $this->getAndCheckForm([
            ['page', '^\\d+$', ],
            ['rows', '^\\d+$', ],
            ['teacher_id', '^\\d+$',],
            ['catalog_id', '^\\d+$',],
            ['recommend', '^\\d+$',],
            ['type', 'integer',],
            ['column_id', 'integer',],
        ]);

        $teacher_id = intval($form['teacher_id'] ?? -1);
        $type = $form['type'] ?? 0;
        $catalog_id = intval($form['catalog_id'] ?? 0);
        $recommend = intval($form['recommend'] ?? 0);
        $column_id = isset($form['column_id']) ? intval($form['column_id']) : 0;
        $params = self::pageFormat($form);

        $re = TeacherEssay::apiList($params['limit'], $params['offset'], $teacher_id, $type, $catalog_id, $recommend, $this->isPC(), $uid, $column_id);

        if ($this->isPC()) return ApiResponse::success($re['list'], $re['total'], $params['limit']);
        else return ApiResponse::success($re);
    }



    /**
     * 热门咨询列表
     *
     * @return ApiResponse
     */
    public function essay_hot() {
        $form = $this->getAndCheckForm([
            ['num', 'integer',],
        ]);
        $num = intval($form['num'] ?? 8);

        $list = TeacherEssay::hotList($num);

        return ApiResponse::success($list);
    }


    /**
     * 大咖观点图文详情
     *
     * @return ApiResponse
     */
    public function essay_detail() {
        $uid = checkUserToken();

        $form = $this->getAndCheckForm([
            ['id', 'require|^\\d+$',],
        ]);

        $id = intval($form['id']);
        $result = TeacherEssay::apiDetail($id, $uid);

        // zk 20180528 被绑定成为课程服务的文章检测课程是否已被购买
        $form['course_id'] = $form['course_id']??0;
        $bind_course = json_decode($result['bind_course'],true);
        if (count($bind_course)) {
            if ((($result['catalog_id']==config('course_serivce.internalReferenceId')) || ($result['catalog_id']==config('course_serivce.researchReportId')))) {
                if ($form['course_id']>0) {
                    $isBuy = \app\api\model\TeacherEssay::checkBingCourseArticleIsBuy($uid, $form['id'], $form['course_id']);
                    if (!$isBuy) return ApiResponse::error(ApiResponse::ERR_NO_PURCHASE,'您还未购买该课程');
                } else {
                    return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'资讯不存在');
                }
            }
        }
        unset($result['bind_course']);

        if (empty($result)) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'资讯不存在');

        TeacherEssay::click($result['id']);
        if ($this->isPC()) {
            if ($result['teacher_id'] > 0) {
                $result['teacher'] = Teacher::apiDetail($result['teacher_id'], $uid);
                $result['recommend_essay'] = TeacherEssay::getByTeacher($result['teacher_id'],8);
            }
            else {
                $result['banners'] = Banner::apiList(Banner::PAGE_PC_ESSAY_DETAIL);
                $result['recommend_essay'] = TeacherEssay::getByTeacher(0,8);
            }
        }

        return ApiResponse::success($result);
    }

    /**
     * 大咖观点图文详情
     *
     * @return ApiResponse
     */
    public function essay_detail_app() {
        $uid = checkUserToken();

        $form = $this->getAndCheckForm([
            ['id', 'require|^\\d+$',],
        ]);

        $id = intval($form['id']);
        $result = TeacherEssay::apiDetail($id, $uid, true);
        if (empty($result)) {
            return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'文章不存在');
        }
        TeacherEssay::click($result['id']);

        return ApiResponse::success($result);
    }

    public function gave_like_to_essay() {

        $uid = checkUserToken(true);

        $form = $this->getAndCheckForm([
            ['essay_id', 'require|integer'],
            ['cancel', 'integer'],
        ]);

        $re = TeacherEssay::gave_like($uid, intval($form['essay_id']), empty($form['cancel']));

        if ($re) return ApiResponse::success();
        else return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED);
    }

    /**
     * 收藏图文
     * 需要登录
     *
     * @return ApiResponse
     */
    public function collect_essay() {

        $uid = checkUserToken(true);

        $form = $this->getAndCheckForm([
            ['essay_id', 'require|integer'],
            ['cancel', 'integer'],
        ]);

        $re = TeacherEssay::collect($uid,intval($form['essay_id']), empty($form['cancel']));
        if ($re) return ApiResponse::success();
        else return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED);
    }

    /**
     * 收藏图文
     * 需要登录
     *
     * @return ApiResponse
     */
    public function essay_collection_list() {

        $uid = checkUserToken(true);

        $form = $this->getAndCheckForm([
            ['page', 'integer',],
            ['rows', 'integer',],
        ]);

        $rows = intval($form['rows']??10);
        $re = TeacherEssay::collectionList($uid, $rows, intval($form['page']??1),$this->isPC());
        if ($this->isPC()) return ApiResponse::success($re['list'], $re['total'], $rows);
        else return ApiResponse::success($re);
    }


    /**
     * 首页大咖说
     *
     * @return ApiResponse
     */
    public function speaking() {

        $form = $this->getAndCheckForm([
            ['teacher_id', '^\\d+$',],
            ['page', '^\\d+$',],
            ['rows', '^\\d+$',],
        ]);

        $teacher_id = intval($form['teacher_id'] ?? 0);

        $params = self::pageFormat($form);
        $re = TeacherSpeaking::apiList($params['limit'], $params['offset'], $teacher_id, $this->isPC());

        if ($this->isPC()) return ApiResponse::success($re['list'], $re['total'],$params['limit']);
        return ApiResponse::success($re);
    }

    /**
     * 加关注和取消
     * 需要登录
     *
     * @return ApiResponse
     */
    public function follow() {

        $uid = checkUserToken(true);
        $form = $this->getAndCheckForm([
            ['teacher_id', 'require|^\\d+$', '老师ID不能为空|参数类型不正确'],
            ['cancel', '^\\d+$', '参数类型不正确'],
        ]);

        $teacher_id = intval($form['teacher_id']);
        $cancel = intval($form['cancel'] ?? 0);

        Teacher::follow($teacher_id, $uid, $cancel);

        return ApiResponse::success();
    }

    /**
     * 我关注的老师列表
     * 需要登录
     *
     * @return ApiResponse
     */
    public function followed_teachers() {

        $uid = checkUserToken(true);

        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
        ]);

        $params = self::pageFormat($form);
        $re = Teacher::followedList($uid, $params['limit'], $params['offset'], $this->isPC());

        if ($this->isPC()) return ApiResponse::success($re['list'], $re['total'], $params['limit']);
        else return ApiResponse::success($re);
    }

    /**
     * teacher_video
     * 大咖(免费)课程视频数据接口
     * @api http://xxx/api/teacher/curriculum_video
     *      teacher_id 必填 老师id
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @return \think\response\Json
     */
    public function teacher_video()
    {
        $curriculumM = new \app\api\model\curriculum\Curriculum();

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['teacher_id', 'require|^\\d+$', '老师ID不能为空|参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        if (!array_key_exists('page', $form) || empty($form['page'])) $form['page']=1;
        if (!array_key_exists('rows', $form) || empty($form['rows'])) $form['rows']=10;

        return $curriculumM->get_teacher_video($form['teacher_id'], $form['page'], $form['rows']);
    }

    /**
     * teacher_curriculum
     * 大咖课程数据接口
     * @api http://xxx/api/teacher/curriculum
     *      teacher_id 必填 老师id
     *      page 选填 当前页数
     *      rows 选真 每页加载数据条数
     *
     * @return \think\response\Json
     */
    public function teacher_curriculum()
    {
        $uid = checkUserToken(false);

        $curriculumM = new \app\api\model\curriculum\Curriculum();

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['teacher_id', 'require|^\\d+$', '老师ID不能为空|参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        if (!array_key_exists('page', $form) || empty($form['page'])) $form['page']=1;
        if (!array_key_exists('rows', $form) || empty($form['rows'])) $form['rows']=3;

        return $curriculumM->get_teacher_curriculum($form['teacher_id'], $uid, $form['page'], $form['rows'],$this->isPC());
    }

    /*public function teacherCurriculumWeb()
    {
        $uid = checkUserToken(false);

        $curriculumM = new \app\api\model\curriculum\Curriculum();

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['teacher_id', 'require|^\\d+$', '老师ID不能为空|参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        if (!array_key_exists('page', $form) || empty($form['page'])) $form['page']=1;
        if (!array_key_exists('rows', $form) || empty($form['rows'])) $form['rows']=3;

        return $curriculumM->get_teacher_curriculum($form['teacher_id'], $uid, $form['page'], $form['rows'],true);
    }*/


    /**
     * ask
     * 老师问答列表
     * @api POST http://xxx/api/teachers/ask
     *      teacher_id  必填  老师id
     *      page        选填  当前页数，默认1
     *      limit       选填  每页加载数，默认10
     *
     * @author zhengkai
     * @date 2018-03-09
     * @version 1.4
     *
     * @return ApiResponse
     */
    public function ask()
    {
        $uid = checkUserToken(false);
        $form = $this->getAndCheckForm([
            ['teacher_id', 'require|integer', '老师id不能为空'],
            ['page', 'integer',],
            ['limit', 'integer',],
        ]);

        if (!isset($form['page'])) $form['page'] = 1;
        if (!isset($form['limit'])) $form['limit'] = 10;

        $result = \app\api\model\ask\Ask::teacherAsk($form['teacher_id'], $uid, $form['page'], $form['limit']);

        return ApiResponse::success($result);
    }



    public function article() {

        $uid = checkUserToken();

        $form = $this->getAndCheckForm([
            ['teacher_id', 'require|integer',],
            ['page', 'integer',],
            ['limit', 'integer',],
        ]);
        $teacherId = intval($form['teacher_id']);
        $page = intval($form['page'] ?? 1);
        $rows = intval($form['rows'] ?? 10);
        $now = time();

        $result = [];
        if (1 == $page) {
            $columnList = SpecialColumn::all(function (Query $query) use ($teacherId, $rows, $uid) {
                $query->where('column_teacher','=', $teacherId);
                $query->where('column_status','=',0);
                $query->field("column_id,column_title,column_description,covers->>'list' column_cover,column_price,column_expiry,column_createtime,column_updatetime,
                (select uss.ust_expiry_date from user_subscribe_special uss where uss.ust_special=column_id and uss.ust_user={$uid}) ust_expiry_date");
                $query->page(1, $rows);
                $query->order('column_id','desc');
            });
            foreach ($columnList as $col) {
                if ($col->column_updatetime) $col->column_updatetime = tranTime($col->column_updatetime);
                else $col->column_updatetime = tranTime($col->column_createtime);
                $col->free = $col->isFree();
                if (is_null($col->ust_expiry_date)) {
                    $col->column_subscribe_status = 0;
                    $col->expiry_day = 0;
                } else {
                    $col->column_subscribe_status = ($col->ust_expiry_date > $now ? 1 : 2);
                    if ($col->ust_expiry_date > $now) {
                        $col->column_subscribe_status = 1;
                        $col->expiry_day = round(($col->ust_expiry_date - $now) / (3600*24), 0);
                    } else {
                        $col->column_subscribe_status = 2;
                        $col->expiry_day = 0;
                    }
                }
                $col->column_subscribe_total = UserSubscribeSpecial::totalSubscribe($col->column_id);

                unset($col->column_createtime, $col->ust_expiry_date);

                $result[] = ['item_type' => 1, 'column' => $col, 'article' => new \stdClass()];
            }
            unset($col);
            $rows -= count($columnList);
        }
        if ($rows > 0) {
            $essays = TeacherEssay::all(function (Query $query) use ($teacherId, $page, $rows) {
                $query->alias('e')->join('teacher t','t.id=e.teacher_id');
                $query->where('e.teacher_id','=', $teacherId);
                $query->where('e.special_column_id','=',0);
                $query->field('e.id,e.title,e.summary,e.cover,e.created,t.realname teacher_name');
                $query->page($page, $rows);
                $query->order('e.id','desc');
            });

            foreach ($essays as $essay) {
                $essay->created = tranTime(strtotime($essay->created));
                $result[] = ['item_type' => 2, 'column' => new \stdClass(), 'article' => $essay];
            }
            unset($essay);
        }

        return ApiResponse::success($result);
    }

    /**
     * web_list
     * @api POST http://xxx/api/teachers/web_list
     *      page 选填 当前第几页，默认1
     *      limit   选填 每页获取数据条数，默认10
     *
     * @author zhengkai
     * @date 2018-04-24
     * @version version 1.4.1
     *
     * @return ApiResponse
     */
    public function web_list()
    {
        $form = $this->getAndCheckForm([
            ['page', 'integer',],
            ['limit', 'integer',],
        ]);
        $page = intval($form['page'] ?? 1);
        $limit = intval($form['limit'] ?? 10);


        $result = \app\api\model\Teacher::getTeacherSimpleList($page, $limit);

        return ApiResponse::success($result);
    }

    /**
     * special
     * 老师专栏数据接口
     * @api POST http://xxx/api/teachers/special
     *      teacher_id 必填 老师id
     *
     * @author zhengkai
     * @date 2018-04-24
     * @version 1.4.1
     *
     * @return ApiResponse
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function special()
    {
        $form = $this->getAndCheckForm([
            ['teacher_id', 'require|integer', '老师id不能为空|参数类型不正确'],
        ]);

        $result = SpecialColumn::getTeacherColumn($form['teacher_id']);

        return ApiResponse::success($result);
    }
}